<!-- src/views/ContractPaymentManagement.vue -->
<template>
  <div class="page-container">
    <!-- 页面头部 -->
    <PageHeader title="合同付款管理">
      <!-- 搜索和筛选区域 -->
      <template #search-filters>
        <!-- 付款搜索 -->
        <div class="payment-search">
          <span class="label">付款搜索：</span>
          <el-tooltip content="支持搜索付款编号、付款摘要" placement="top">
            <el-icon class="help-icon"><QuestionFilled /></el-icon>
          </el-tooltip>
          <el-input
            v-model="searchParams.search"
            placeholder="搜索付款编号、付款摘要"
            style="width: 300px"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <!-- 合同选择 -->
        <div class="contract-select">
          <span class="label">选择合同：</span>
          <el-tooltip content="选择合同进行筛选" placement="top">
            <el-icon class="help-icon"><QuestionFilled /></el-icon>
          </el-tooltip>
          <el-select
            v-model="searchParams.contractId"
            placeholder="选择合同"
            clearable
            filterable
            style="width: 200px"
            @change="handleSearch"
          >
            <el-option 
              v-for="contract in contractList" 
              :key="contract.id" 
              :label="contract.contractName" 
              :value="contract.id" 
            />
          </el-select>
        </div>

        <!-- 付款方选择 -->
        <div class="payment-side-select">
          <span class="label">付款方：</span>
          <el-tooltip content="选择付款方进行筛选" placement="top">
            <el-icon class="help-icon"><QuestionFilled /></el-icon>
          </el-tooltip>
          <el-select
            v-model="searchParams.paymentSide"
            placeholder="付款方"
            filterable
            clearable
            style="width: 150px"
            @change="handleSearch"
          >
            <el-option label="甲方" :value="1" />
            <el-option label="乙方" :value="2" />
          </el-select>
        </div>
      </template>

      <!-- 主要操作按钮 -->
      <template #main-actions>
        <el-button @click="handleAdd" type="primary">
          <el-icon><Plus /></el-icon>
          新建付款记录
        </el-button>
      </template>

      <!-- 更多操作下拉菜单 -->
      <template #more-actions>
        <el-dropdown @command="handleMoreAction">
          <el-button type="info">
            <el-icon><More /></el-icon>
            更多
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="export">
                <el-tooltip content="导出当前筛选条件下的所有付款记录为Excel文件" placement="left">
                  <div style="display: flex; align-items: center; gap: 8px;">
                    <el-icon><Download /></el-icon>
                    导出Excel
                  </div>
                </el-tooltip>
              </el-dropdown-item>
              <el-dropdown-item command="columnConfig" icon="Setting">列配置</el-dropdown-item>
              <el-dropdown-item command="reset" icon="Refresh" divided>重置筛选</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </PageHeader>

    <!-- 数据表格 -->
    <div class="table-container">
      <!-- 使用 BaseTable 组件 -->
      <BaseTable
        table-name="contractPayment"
        :columns="tableColumns"
        :data="state.pageData"
        :loading="state.loading"
        :sort="sort"
        @sort-change="handleSortChange"
      >
        <!-- 付款方插槽 -->
        <template #paymentSide="{ row }">
          <el-tag :type="getPaymentSideTag(row.paymentSide)">
            {{ getPaymentSideName(row.paymentSide) }}
          </el-tag>
        </template>
        
        <!-- 付款金额插槽 -->
        <template #paymentAmount="{ row }">
          <span class="amount-text">¥{{ formatAmount(row.paymentAmount) }}</span>
        </template>
        
        <!-- 付款日期插槽 -->
        <template #paymentDate="{ row }">
          {{ formatDate(row.paymentDate) }}
        </template>
        
        <!-- 操作列插槽 -->
        <template #actions="{ row }">
          <div class="action-buttons">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="success" size="small" @click="showAttachments(row)">
              <el-icon><Document /></el-icon>
              附件
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </div>
        </template>
      </BaseTable>

      <!-- 分页器 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="state.currentPage"
          v-model:page-size="state.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="state.totalItems"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新建/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="800px"
      @close="resetForm"
    >
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
        class="payment-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="付款编号" prop="paymentNumber">
              <el-input 
                v-model="form.paymentNumber" 
                placeholder="请输入付款编号"
                @blur="checkPaymentNumberUnique"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款日期" prop="paymentDate">
              <el-date-picker
                v-model="form.paymentDate"
                type="date"
                placeholder="选择付款日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="付款金额" prop="paymentAmount">
              <el-input-number
                v-model="form.paymentAmount"
                :precision="2"
                :min="0"
                :max="999999999"
                style="width: 100%"
                placeholder="请输入付款金额"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款方" prop="paymentSide">
              <el-select v-model="form.paymentSide" placeholder="选择付款方" style="width: 100%">
                <el-option label="甲方" :value="1" />
                <el-option label="乙方" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关联合同" prop="contractId">
              <el-select 
                v-model="form.contractId" 
                placeholder="选择关联合同" 
                style="width: 100%"
                filterable
              >
                <el-option 
                  v-for="contract in contractList" 
                  :key="contract.id" 
                  :label="contract.contractName" 
                  :value="contract.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="凭证号" prop="voucherNumber">
              <el-input v-model="form.voucherNumber" placeholder="请输入凭证号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="付款摘要" prop="paymentSummary">
          <el-input 
            v-model="form.paymentSummary" 
            type="textarea" 
            :rows="3"
            placeholder="请输入付款摘要"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商账户名称" prop="supplierAccountName">
              <el-input v-model="form.supplierAccountName" placeholder="请输入供应商账户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款账户" prop="paymentAccount">
              <el-input v-model="form.paymentAccount" placeholder="请输入付款账户" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商开户行" prop="supplierBankName">
              <el-input v-model="form.supplierBankName" placeholder="请输入供应商开户行" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商银行账号" prop="supplierBankAccount">
              <el-input v-model="form.supplierBankAccount" placeholder="请输入供应商银行账号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 附件上传区域 -->
        <el-form-item label="附件上传">
          <div class="attachment-upload-area">
            <el-upload
              ref="uploadRef"
              :action="uploadAction"
              :headers="uploadHeaders"
              :data="uploadData"
              :file-list="uploadFileList"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :on-remove="handleUploadRemove"
              :before-upload="beforeUpload"
              :limit="10"
              :show-file-list="false"
              multiple
              drag
              class="upload-demo"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持任意文件类型，单个文件不超过50MB，最多上传10个文件
                </div>
              </template>
            </el-upload>
            
            <!-- 已上传附件列表 -->
            <div v-if="form.attachments && form.attachments.length > 0" class="uploaded-attachments">
              <h4>已上传附件</h4>
              <div class="attachment-list">
                <div v-for="attachment in form.attachments" :key="attachment.id" class="attachment-item">
                  <div class="attachment-info">
                    <div class="attachment-name">{{ attachment.originalFilename }}</div>
                    <div class="attachment-meta">
                      <span class="file-size">{{ formatFileSize(attachment.fileSize) }}</span>
                      <span class="file-type">{{ attachment.fileType }}</span>
                      <span v-if="attachment.subDirectory" class="sub-directory">目录: {{ attachment.subDirectory }}</span>
                    </div>
                  </div>
                  <div class="attachment-actions">
                    <el-button 
                      type="danger" 
                      size="small" 
                      circle
                      @click="removeAttachment(attachment)"
                      class="delete-btn"
                    >
                      <el-icon><Close /></el-icon>
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 附件对话框 -->
    <el-dialog 
      v-model="attachmentDialogVisible" 
      title="付款记录附件" 
      width="800px"
      class="attachment-dialog"
    >
      <div class="attachment-content">
        <!-- 付款记录信息 -->
        <div class="payment-info" v-if="selectedPayment">
          <h4>付款记录信息</h4>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">付款编号:</span>
              <span class="value">{{ selectedPayment.paymentNumber }}</span>
            </div>
            <div class="info-item">
              <span class="label">付款日期:</span>
              <span class="value">{{ formatDate(selectedPayment.paymentDate) }}</span>
            </div>
            <div class="info-item">
              <span class="label">付款金额:</span>
              <span class="value">¥{{ formatAmount(selectedPayment.paymentAmount) }}</span>
            </div>
            <div class="info-item">
              <span class="label">付款摘要:</span>
              <span class="value">{{ selectedPayment.paymentSummary }}</span>
            </div>
          </div>
        </div>
        
        <!-- 附件列表 -->
        <div class="attachment-list" v-if="attachmentList.length > 0">
          <div class="attachment-item" v-for="attachment in attachmentList" :key="attachment.id">
            <div class="attachment-info">
              <div class="attachment-name">{{ attachment.originalFilename }}</div>
              <div class="attachment-meta">
                <span class="file-size">{{ formatFileSize(attachment.fileSize) }}</span>
                <span class="file-type">{{ attachment.fileType }}</span>
                <span class="upload-time">{{ formatAttachmentDate(attachment.createTime) }}</span>
                <span v-if="attachment.subDirectory" class="sub-directory">目录: {{ attachment.subDirectory }}</span>
              </div>
            </div>
            <div class="attachment-actions">
              <el-button type="primary" size="small" @click="previewAttachment(attachment)">
                <el-icon><View /></el-icon>
                预览
              </el-button>
              <el-button type="success" size="small" @click="downloadAttachment(attachment)">
                <el-icon><Download /></el-icon>
                下载
              </el-button>
            </div>
          </div>
        </div>
        
        <div v-else class="no-attachments">
          <el-empty description="暂无附件" />
        </div>
      </div>
    </el-dialog>

    <!-- 列配置对话框 -->
    <el-dialog v-model="columnConfigVisible" title="列配置" width="600px" class="column-config-dialog">
      <div class="column-config">
        <div class="column-list">
          <div v-for="column in tableColumns" :key="column.prop" class="column-item">
            <div class="column-info">
              <el-checkbox 
                v-model="column.visible" 
                :label="column.label"
                @change="handleColumnVisibilityChange"
              />
            </div>
            <div class="column-width" v-if="column.visible">
              <span class="width-label">宽度:</span>
              <el-input-number
                v-model="column.width"
                :min="80"
                :max="500"
                :step="10"
                size="small"
                style="width: 100px;"
                @change="handleColumnWidthChange"
              />
              <span class="unit">px</span>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetColumnConfig">重置</el-button>
          <el-button type="primary" @click="saveColumnConfig">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { 
  Plus, Search, ArrowDown, Edit, Delete, View, 
  Document, Download, Refresh, Setting, QuestionFilled, More,
  UploadFilled, Close
} from '@element-plus/icons-vue'
import BaseTable from '@/components/tools/BaseTable.vue'
import PageHeader from '@/components/layout/PageHeader.vue'
import useTable from '@/composables/useTable.js'
import contractPaymentApi from '@/api/contractPaymentApi'
import contractApi from '@/api/contractApi'
import attachmentApi from '@/api/attachmentApi'

// 使用通用表格组件
const { state, loadData, handleSortChange, updateSearchParams, handleSizeChange, handleCurrentChange } = useTable(contractPaymentApi.getList)

// 搜索参数
const searchParams = reactive({
  search: '',
  contractId: null,
  paymentSide: null
})

// 排序参数
const sort = ref({})

// 表格列配置 - 包含所有字段，默认显示主要字段
const tableColumns = ref([
  // 主要字段 - 默认显示
  { prop: 'paymentNumber', label: '付款编号', width: 130, visible: true },
  { prop: 'paymentDate', label: '付款日期', width: 120, visible: true, slot: 'paymentDate' },
  { prop: 'paymentSummary', label: '付款摘要', minwidth: 180, visible: true },
  { prop: 'paymentAmount', label: '付款金额', width: 140, visible: true, slot: 'paymentAmount' },
  { prop: 'paymentSide', label: '付款方', width: 100, visible: true, slot: 'paymentSide' },
  { prop: 'supplierAccountName', label: '供应商账户名称', width: 280, visible: true },
  { prop: 'paymentAccount', label: '付款账户', width: 120, visible: false },
  { prop: 'supplierBankName', label: '供应商开户行', width: 140, visible: false },
  { prop: 'supplierBankAccount', label: '供应商银行账号', width: 160, visible: false },
  { prop: 'voucherNumber', label: '凭证号', width: 120, visible: false },
  { prop: 'contractId', label: '关联合同ID', width: 100, visible: false },
  { prop: 'attachmentIds', label: '附件ID列表', width: 100, visible: false },
  { prop: 'createTime', label: '创建时间', width: 160, visible: false },
  { prop: 'updateTime', label: '更新时间', width: 160, visible: false },
  { prop: 'createBy', label: '创建人ID', width: 100, visible: false },
  { prop: 'id', label: 'ID', width: 80, visible: false },
  // 操作列
  { prop: 'actions', label: '操作', width: 280, visible: true, slot: 'actions', fixed: 'right' }
])

// 列配置相关
const columnConfigVisible = ref(false)
const originalTableColumns = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新建付款记录')
const submitLoading = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  id: null,
  paymentNumber: '',
  paymentDate: '',
  paymentSummary: '',
  paymentAmount: null,
  supplierAccountName: '',
  supplierBankName: '',
  supplierBankAccount: '',
  paymentAccount: '',
  paymentSide: null,
  contractId: null,
  voucherNumber: '',
  attachmentIds: '',
  attachments: [] // 新增附件数组
})

// 表单验证规则
const rules = {
  paymentNumber: [
    { required: true, message: '请输入付款编号', trigger: 'blur' },
    { min: 2, max: 50, message: '付款编号长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  paymentDate: [
    { required: true, message: '请选择付款日期', trigger: 'change' }
  ],
  paymentAmount: [
    { required: true, message: '请输入付款金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '付款金额必须大于0', trigger: 'blur' }
  ],
  paymentSide: [
    { required: true, message: '请选择付款方', trigger: 'change' }
  ],
  contractId: [
    { required: true, message: '请选择关联合同', trigger: 'change' }
  ]
}

// 附件相关
const attachmentDialogVisible = ref(false)
const attachmentList = ref([])
const selectedPayment = ref(null)

// 附件上传相关
const uploadRef = ref()
const uploadFileList = ref([])
const uploadAction = '/api/attachments/upload'
const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${localStorage.getItem('token')}`
}))
const uploadData = computed(() => ({
  subDirectory: 'contractpayment'
}))

// 合同列表
const contractList = ref([])

// 搜索处理
const handleSearch = () => {
  updateSearchParams(searchParams)
  loadData()
}

// 更多操作处理
const handleMoreAction = (command) => {
  switch (command) {
    case 'export':
      handleExport()
      break
    case 'columnConfig':
      showColumnConfig()
      break
    case 'reset':
      resetSearch()
      break
  }
}

// 导出Excel
const handleExport = async () => {
  try {
    // 确认导出
    await ElMessageBox.confirm(
      '确定要导出当前筛选条件下的所有付款记录吗？',
      '确认导出',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    ElMessage.info('正在导出Excel文件，请稍候...')
    
    const response = await contractPaymentApi.exportData(searchParams)
    
    // 生成文件名
    const now = new Date()
    const dateStr = now.toISOString().split('T')[0]
    let filename = `付款记录列表_${dateStr}`
    
    // 添加筛选条件到文件名
    if (searchParams.search) {
      filename += `_${searchParams.search}`
    }
    if (searchParams.contractId) {
      const contract = contractList.value.find(c => c.id === searchParams.contractId)
      if (contract) {
        filename += `_${contract.contractName}`
      }
    }
    if (searchParams.paymentSide !== null) {
      filename += `_${getPaymentSideName(searchParams.paymentSide)}`
    }
    
    filename += '.xlsx'
    
    // 下载文件
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('Excel文件导出成功！')
  } catch (error) {
    if (error === 'cancel') return
    
    console.error('导出失败:', error)
    let errorMessage = '导出失败'
    
    if (error.response) {
      switch (error.response.status) {
        case 401:
          errorMessage = '未授权，请重新登录'
          break
        case 403:
          errorMessage = '权限不足，无法导出数据'
          break
        case 400:
          errorMessage = '请求参数错误'
          break
        case 404:
          errorMessage = '导出接口不存在'
          break
        case 500:
          errorMessage = '服务器内部错误'
          break
        default:
          errorMessage = `导出失败: ${error.response.status}`
      }
    } else if (error.request) {
      errorMessage = '网络错误，请检查网络连接'
    }
    
    ElMessage.error(errorMessage)
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchParams, {
    search: '',
    contractId: null,
    paymentSide: null
  })
  handleSearch()
}

// 新建付款记录
const handleAdd = () => {
  dialogTitle.value = '新建付款记录'
  dialogVisible.value = true
  resetForm()
}

// 编辑付款记录
const handleEdit = async (row) => {
  dialogTitle.value = '编辑付款记录'
  dialogVisible.value = true
  Object.assign(form, row)
  
  // 加载现有附件
  if (row.attachmentIds) {
    try {
      const ids = row.attachmentIds.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id))
      if (ids.length > 0) {
        const response = await attachmentApi.getAttachmentsBatch(ids)
        form.attachments = response.data || response || []
      } else {
        form.attachments = []
      }
    } catch (error) {
      console.error('加载附件失败:', error)
      form.attachments = []
    }
  } else {
    form.attachments = []
  }
}

// 删除付款记录
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除付款记录 "${row.paymentNumber}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await contractPaymentApi.deleteById(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error === 'cancel') return
    
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitLoading.value = true
    
    if (form.id) {
      // 更新
      await contractPaymentApi.update(form.id, form)
      ElMessage.success('更新成功')
    } else {
      // 新建
      await contractPaymentApi.create(form)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('提交失败:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('操作失败')
    }
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    paymentNumber: '',
    paymentDate: '',
    paymentSummary: '',
    paymentAmount: null,
    supplierAccountName: '',
    supplierBankName: '',
    supplierBankAccount: '',
    paymentAccount: '',
    paymentSide: null,
    contractId: null,
    voucherNumber: '',
    attachmentIds: '',
    attachments: []
  })
  
  // 清空上传文件列表
  uploadFileList.value = []
  
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 检查付款编号唯一性
const checkPaymentNumberUnique = async () => {
  if (!form.paymentNumber) return
  
  try {
    const response = await contractPaymentApi.checkPaymentNumber(form.paymentNumber, form.id)
    if (!response.data) {
      ElMessage.warning('付款编号已存在，请使用其他编号')
    }
  } catch (error) {
    console.error('检查付款编号失败:', error)
  }
}

// 显示附件
const showAttachments = async (row) => {
  selectedPayment.value = row
  attachmentDialogVisible.value = true
  
  if (row.attachmentIds) {
    try {
      const ids = row.attachmentIds.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id))
      if (ids.length > 0) {
        const response = await attachmentApi.getAttachmentsBatch(ids)
        attachmentList.value = response.data || response || []
      } else {
        attachmentList.value = []
      }
    } catch (error) {
      console.error('获取附件失败:', error)
      ElMessage.error('获取附件失败')
      attachmentList.value = []
    }
  } else {
    attachmentList.value = []
  }
}

// 预览附件
const previewAttachment = async (attachment) => {
  // 显示加载提示
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在加载预览...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    const response = await attachmentApi.previewAttachment(attachment.id)
    const blob = new Blob([response.data], { type: attachment.fileType || 'application/octet-stream' })
    const url = window.URL.createObjectURL(blob)
    window.open(url, '_blank')
    // 清理URL对象
    setTimeout(() => window.URL.revokeObjectURL(url), 1000)
    ElMessage.success('预览已打开')
  } catch (error) {
    console.error('预览附件失败:', error)
    ElMessage.error('预览失败')
  } finally {
    loadingInstance.close()
  }
}

// 下载附件
const downloadAttachment = async (attachment) => {
  // 显示加载提示
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在准备下载...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    const response = await attachmentApi.downloadAttachment(attachment.id)
    const blob = new Blob([response.data], { type: attachment.fileType || 'application/octet-stream' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = attachment.originalFilename || `附件_${attachment.id}`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    // 清理URL对象
    setTimeout(() => window.URL.revokeObjectURL(url), 1000)
    ElMessage.success('下载成功')
  } catch (error) {
    console.error('下载附件失败:', error)
    ElMessage.error('下载失败')
  } finally {
    loadingInstance.close()
  }
}

// 附件上传相关函数
const beforeUpload = (file) => {
  const isLt50M = file.size / 1024 / 1024 < 50
  if (!isLt50M) {
    ElMessage.error('上传文件大小不能超过 50MB!')
    return false
  }
  return true
}

const handleUploadSuccess = (response, file, fileList) => {
  if (response && response.id) {
    // 初始化attachments数组
    if (!form.attachments) {
      form.attachments = []
    }
    
    // 添加新上传的附件
    form.attachments.push(response)
    
    // 更新attachmentIds
    const ids = form.attachments.map(att => att.id)
    form.attachmentIds = ids.join(',')
    
    ElMessage.success('附件上传成功')
  } else {
    ElMessage.error('附件上传失败')
  }
}

const handleUploadError = (error, file, fileList) => {
  console.error('上传失败:', error)
  ElMessage.error('附件上传失败')
}

const handleUploadRemove = (file, fileList) => {
  // 由于show-file-list为false，这个函数实际上不会被调用
  // 但保留以防万一
  if (form.attachments) {
    const index = form.attachments.findIndex(att => att.originalFilename === file.name)
    if (index > -1) {
      form.attachments.splice(index, 1)
      // 更新attachmentIds
      const ids = form.attachments.map(att => att.id)
      form.attachmentIds = ids.join(',')
    }
  }
}

const removeAttachment = async (attachment) => {
  try {
    await ElMessageBox.confirm('确定要删除这个附件吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用删除API
    await attachmentApi.deleteAttachment(attachment.id)
    
    // 从本地列表中移除
    if (form.attachments) {
      const index = form.attachments.findIndex(att => att.id === attachment.id)
      if (index > -1) {
        form.attachments.splice(index, 1)
        // 更新attachmentIds
        const ids = form.attachments.map(att => att.id)
        form.attachmentIds = ids.join(',')
      }
    }
    
    ElMessage.success('附件删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除附件失败:', error)
      ElMessage.error('删除附件失败')
    }
  }
}

// 列配置相关函数
const showColumnConfig = () => {
  columnConfigVisible.value = true
}

const handleColumnVisibilityChange = () => {
  // 触发表格重新渲染
  nextTick(() => {
    // 这里可以添加表格重新渲染的逻辑
  })
}

const handleColumnWidthChange = () => {
  // 触发表格重新渲染
  nextTick(() => {
    // 这里可以添加表格重新渲染的逻辑
  })
}

const resetColumnConfig = () => {
  // 重置为原始配置
  tableColumns.value = JSON.parse(JSON.stringify(originalTableColumns.value))
}

const saveColumnConfig = () => {
  // 保存到localStorage
  localStorage.setItem('contractPaymentTableColumns', JSON.stringify(tableColumns.value))
  columnConfigVisible.value = false
  ElMessage.success('列配置已保存')
}

// 工具函数
const getPaymentSideName = (paymentSide) => {
  const paymentSideMap = {
    1: '甲方',
    2: '乙方'
  }
  return paymentSideMap[paymentSide] || '未知'
}

const getPaymentSideTag = (paymentSide) => {
  const tagMap = {
    1: 'primary',
    2: 'success'
  }
  return tagMap[paymentSide] || 'info'
}

const formatAmount = (amount) => {
  if (!amount) return '0.00'
  return Number(amount).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatAttachmentDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour12: false })
}

// 加载合同列表
const loadContractList = async () => {
  try {
    const response = await contractApi.getList({ size: 1000 })
    contractList.value = response.data.content || []
  } catch (error) {
    console.error('加载合同列表失败:', error)
  }
}

// 初始化
onMounted(async () => {
  // 加载合同列表
  await loadContractList()
  
  // 保存原始列配置
  originalTableColumns.value = JSON.parse(JSON.stringify(tableColumns.value))
  
  // 从localStorage加载列配置
  const savedColumns = localStorage.getItem('contractPaymentTableColumns')
  if (savedColumns) {
    try {
      const parsedColumns = JSON.parse(savedColumns)
      tableColumns.value = parsedColumns
    } catch (error) {
      console.error('加载列配置失败:', error)
    }
  }
  
  // 加载数据
  loadData()
})
</script>

<style scoped>
.page-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
  overflow: hidden;
}

/* 搜索区域样式 */
.payment-search,
.contract-select,
.payment-side-select {
  display: flex;
  align-items: center;
  gap: 8px;
}

.label {
  color: var(--primary-color, #409eff);
  font-weight: 500;
  white-space: nowrap;
}

.help-icon {
  color: #909399;
  font-size: 14px;
  margin-left: 4px;
  cursor: pointer;
  transition: color 0.3s ease;
}

.help-icon:hover {
  color: var(--primary-color, #409eff);
}

.table-container {
  flex: 1;
  width: 100%;
  min-height: 0;
  max-width: 100%;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.05);
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-sizing: border-box;
}

/* 表格样式与主题协调 */
.table-container :deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

.table-container :deep(.el-table__header) {
  background: var(--primary-color, #409eff);
}

.table-container :deep(.el-table__body tr:hover) {
  background-color: rgba(64, 158, 255, 0.1);
}

.amount-text {
  font-weight: normal;
  color: #333;
}

/* 分页器样式 */
.pagination-wrapper {
  padding: 20px;
  background: white;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top: 1px solid #e4e7ed;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  margin-top: 10px;
  border-radius: 0 0 8px 8px;
  flex-shrink: 0;
  min-height: 60px;
}

.pagination-wrapper .el-pagination {
  --el-pagination-bg-color: transparent;
  --el-pagination-text-color: #606266;
  --el-pagination-border-radius: 4px;
  --el-pagination-button-color: #606266;
  --el-pagination-button-bg-color: #ffffff;
  --el-pagination-button-disabled-color: #c0c4cc;
  --el-pagination-button-disabled-bg-color: #ffffff;
  --el-pagination-hover-color: #409eff;
  --el-pagination-hover-bg-color: #ecf5ff;
}

.pagination-wrapper .el-pagination .el-pager li {
  border-radius: 4px;
  margin: 0 2px;
  transition: all 0.3s ease;
}

.pagination-wrapper .el-pagination .el-pager li.is-active {
  background-color: #409eff;
  color: white;
  font-weight: 600;
}

.pagination-wrapper .el-pagination .el-pager li:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.pagination-wrapper .el-pagination .btn-prev,
.pagination-wrapper .el-pagination .btn-next {
  border-radius: 4px;
  margin: 0 4px;
  transition: all 0.3s ease;
}

.pagination-wrapper .el-pagination .btn-prev:hover,
.pagination-wrapper .el-pagination .btn-next:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.pagination-wrapper .el-pagination .el-pagination__sizes {
  margin-right: 15px;
}

.pagination-wrapper .el-pagination .el-pagination__jump {
  margin-left: 15px;
}

/* 分页器响应式设计 */
@media (max-width: 768px) {
  .pagination-wrapper {
    padding: 15px 10px;
  }
  
  .pagination-wrapper .el-pagination {
    font-size: 12px;
  }
  
  .pagination-wrapper .el-pagination .el-pagination__sizes {
    margin-right: 10px;
  }
  
  .pagination-wrapper .el-pagination .el-pagination__jump {
    margin-left: 10px;
  }
}

@media (max-width: 480px) {
  .pagination-wrapper {
    flex-direction: column;
    gap: 10px;
  }
  
  .pagination-wrapper .el-pagination {
    justify-content: center;
  }
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.table-container .base-table-container {
  flex: 1;
  width: 100%;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

/* 表格样式与主题协调 */
.table-container :deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

.table-container :deep(.el-table__header) {
  background: var(--primary-color, #409eff);
}

.table-container :deep(.el-table__header th) {
  background: var(--primary-color, #409eff) !important;
  color: white !important;
  font-weight: 600;
}

.table-container :deep(.el-table__body tr:hover) {
  background-color: rgba(64, 158, 255, 0.1);
}

/* 表单样式 */
.payment-form {
  max-height: 60vh;
  overflow-y: auto;
}

/* 附件对话框样式 */
.attachment-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.attachment-dialog :deep(.el-dialog__header) {
  background: var(--primary-color, #409eff);
  color: white;
  padding: 20px;
  margin: 0;
}

.attachment-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.attachment-content {
  max-height: 500px;
  overflow-y: auto;
}

.payment-info {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.payment-info h4 {
  color: var(--primary-color, #409eff);
  margin: 0 0 10px 0;
  font-size: 18px;
  font-weight: 600;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item .label {
  font-weight: 500;
  color: #666;
  margin-right: 8px;
  min-width: 80px;
}

.info-item .value {
  color: #333;
  flex: 1;
}

.attachment-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.attachment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fafafa;
  transition: all 0.3s;
}

.attachment-item:hover {
  border-color: var(--primary-color, #409eff);
  background: #f0f8ff;
}

.attachment-info {
  flex: 1;
}

.attachment-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
  font-size: 14px;
}

.attachment-meta {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #909399;
}

.attachment-actions {
  display: flex;
  gap: 8px;
}

.no-attachments {
  text-align: center;
  padding: 40px 20px;
}

/* 附件上传区域样式 */
.attachment-upload-area {
  .upload-demo {
    width: 100%;
    
    .el-upload-dragger {
      width: 100%;
      height: 80px;
      border: 2px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: border-color 0.3s;
      
      &:hover {
        border-color: #409eff;
      }
      
      .el-icon--upload {
        font-size: 20px;
        color: #8c939d;
        width: 40px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        margin-bottom: 8px;
      }
      
      .el-upload__text {
        color: #606266;
        font-size: 12px;
        text-align: center;
        
        em {
          color: #409eff;
          font-style: normal;
        }
      }
    }
    
    .el-upload__tip {
      color: #909399;
      font-size: 12px;
      margin-top: 8px;
    }
  }
  
  .uploaded-attachments {
    margin-top: 15px;
    
    h4 {
      font-size: 13px;
      color: #303133;
      margin-bottom: 8px;
      font-weight: 600;
    }
    
    .attachment-list {
      .attachment-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 12px;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        margin-bottom: 6px;
        background: #fafafa;
        
        &:hover {
          background: #f5f7fa;
          border-color: #c0c4cc;
        }
        
        .attachment-info {
          flex: 1;
          
          .attachment-name {
            font-size: 13px;
            color: #303133;
            margin-bottom: 3px;
            font-weight: 500;
          }
          
          .attachment-meta {
            display: flex;
            gap: 12px;
            font-size: 11px;
            color: #909399;
            
            .sub-directory {
              color: #409eff;
              font-weight: 500;
            }
          }
        }
        
        .attachment-actions {
          display: flex;
          gap: 8px;
          
          .delete-btn {
            width: 24px;
            height: 24px;
            padding: 0;
            border-radius: 50%;
            
            .el-icon {
              font-size: 12px;
            }
          }
        }
      }
    }
  }
}

/* 列配置对话框样式 */
.column-config-dialog {
  .column-config {
    max-height: 50vh;
    overflow-y: auto;
    
    .column-list {
      .column-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px;
        border-bottom: 1px solid #eee;
        
        &:last-child {
          border-bottom: none;
        }
        
        .column-info {
          flex: 1;
        }
        
        .column-width {
          display: flex;
          align-items: center;
          gap: 8px;
          
          .width-label {
            font-size: 12px;
            color: #666;
          }
          
          .unit {
            font-size: 12px;
            color: #666;
          }
        }
      }
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 10px;
  }
  
  .page-header {
    padding: 15px;
  }
  
  .header-row {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .search-area {
    flex-direction: column;
    gap: 10px;
  }
  
  .action-area {
    justify-content: center;
  }
  
  .table-container {
    padding: 15px;
  }
  
  .attachment-dialog .payment-info .info-grid {
    grid-template-columns: 1fr;
  }
}
</style>
